#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>

#define BUF_SIZE 100
#define NAME_SIZE 20

void * recv_msg(void * arg);
void error_handling(char * msg);

char name[NAME_SIZE]="[DEFAULT]";
char msg[BUF_SIZE];

int main(int argc, char *argv[])
{
	int sockfd;
	struct sockaddr_in servaddr;
	pthread_t snd_thread, rcv_thread;
	void * thread_return;

	if (argc != 4)
		err_quit("Usage: DataClient_Thread <IPAddress> <PortNumber> <FileName>");

	strcpy(name, argv[3]);

	sockfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	servaddr.sin_addr.s_addr = inet_addr(argv[1]);
	servaddr.sin_port = htons(atoi(argv[2]));

	if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
		err_sys("connect error");

	pthread_create(&rcv_thread, NULL, recv_msg, (void*)&sockfd);
	pthread_join(rcv_thread, &thread_return);
	close(sockfd);
	return 0;
}

void * recv_msg(void * arg)   // read thread main
{
	int sock=*((int*)arg);
	char name_msg[NAME_SIZE+BUF_SIZE];
	int str_len;
	FILE *fp1;

	if((fp1 = fopen("Output.txt", "w")) == NULL)
	{
		printf("파일을 생성하지 못했습니다.");
		return 0;
	} else {
		printf("생성 완료\n");
	}

	while(1)
	{
		sprintf(name_msg,"%s", name);
		write(sock, name_msg, strlen(name_msg));

		while((str_len = readline(sock, name_msg, NAME_SIZE+BUF_SIZE-1)) > 0) {
			if(str_len==-1)
				return (void*)-1;
			name_msg[str_len]=0;
			if (fputs(name_msg, fp1) == EOF) {
				err_sys("fputs error");
			}

		}
		printf("Server로부터 수신을 완료했습니다.\n");
		fclose(fp1);
		exit(0);
	}


	return NULL;
}

void error_handling(char *msg)
{
	fputs(msg, stderr);
	fputc('\n', stderr);
	exit(1);
}
